package jobs

import (
	"errors"
	"os"

	md "youbei/models"
	db "youbei/utils/database"
	filedump "youbei/utils/file"
	rs "youbei/utils/rs"
)

//TestBackup ...
func TestBackup(t *md.Task) (string, error) {
	var zipfile string
	var err error
	if t.DBType == "mysql" {
		zipfile, err = db.MysqlSQLDump(t.Host, t.Port, t.DBname, t.User, t.Password, t.Char, t.SavePath, t.Zippwd)
	} else if t.DBType == "mssql" {
		zipfile, err = db.MssqlSQLDump(t.Host, t.Port, t.DBname, t.User, t.Password, t.SavePath, t.Zippwd)
	} else if t.DBType == "sqlite" {
		zipfile, err = db.SqliteSQLDump(t.DBpath, t.SavePath, t.Zippwd)
	} else if t.DBType == "postgres" {
		zipfile, err = db.PostgresSQLDump(t.Host, t.Port, t.DBname, t.User, t.Password, t.SavePath, t.Zippwd)
	} else if t.DBType == "file" {
		zipfile, err = filedump.FileDump(t.DBpath, t.SavePath, t.Zippwd)
	} else {
		err = errors.New("dbtype not found")
	}
	return zipfile, err
}

//TestRemote ...
func TestRemote(zipfile string, v md.RemoteStorage) error {
	yuancheng := rs.NewRS(v.Host, v.Port, v.Username, v.Password, zipfile, v.Path)
	var err error
	if v.Types == "ftp" {
		err = yuancheng.FtpUpload()
	} else if v.Types == "sftp" {
		f, err := yuancheng.NewSftp()
		if err == nil {
			err = f.Upload()
		}
	} else if v.Types == "Yserver" {
		fp, err := yuancheng.ReadBigFile()
		if err != nil {
			return err
		}
		file, err := os.OpenFile(yuancheng.SrcFilePath, os.O_RDONLY, os.ModePerm)
		defer file.Close()
		if err != nil {
			return err
		}

		for _, v := range fp.Packets {
			err = fp.CreatePacket(file, v)
		}
	}
	return err
}
